package com.whately.core.base.keygen;

import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 简单的id生成器  16位
 * 根据时间戳11+机器码1+4位自增数字产生
 */
public class IncreaseIdUtil {

    private final static int maxSequence = 9999;

    //机器码
    private String machineCodeStr ;

    // 带时间的序列，原子操作
    private AtomicStampedReference<StampedSequence> current;

    public IncreaseIdUtil(){
        current = StampedSequence.initRefer();
        this.machineCodeStr = String.valueOf(WhatelyMachineCodeHelper.getMachineCode());
    }


    public IdInfo nextIdModel() {
        StampedSequence seq = StampedSequence.nextSequence(current,maxSequence);
        IdInfo idInfo = new IdInfo(buildingId(seq),seq.getTs());
        return idInfo;
    }

    /**
     * 根据时间戳11+机器码1+4位自增数字产生
     * @return
     */
    public long nextId(){
        StampedSequence seq = StampedSequence.nextSequence(current,maxSequence);
        return buildingId(seq);
    }

    private long buildingId(StampedSequence seq){
        long tsAfterEpoch = seq.getTs()- ConstantsIdGenerator.epoch_20200101_ms;
        long id =  new BigInteger(tsAfterEpoch+ machineCodeStr + StringUtils.leftPad(""+seq.getSequence(),4,"0")).longValue();
        return id;
    }

    public static void main(String[] args) {
        IncreaseIdUtil u = new IncreaseIdUtil();
        for (int i = 0; i < 300; i++) {
            long seq = u.nextId();
            System.out.println(seq);
        }
    }
}
